package sm.upgrade;

import java.util.Collections;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.orm.hibernate3.HibernateTemplate;

import sm.dam.api.DBDictService;
import sm.dbdict.DBDictUtil;
import sm.dbdict.def.DBDict;
import sm.dbdict.def.Field;
import sm.dbdict.def.SqlFieldOptions;
import sm.upgrade.api.UpgradePhase;
import sm.util.SMMap;

public class PriorityUpgrade implements UpgradePhase {

	private static Logger logger = LoggerFactory.getLogger(UpgradePhase.class);

	private HibernateTemplate template;

	public void setTemplate(HibernateTemplate template) {
		this.template = template;
	}

	@Override
	public void upgrade() {
		logger.info("Upgrading Priority Code...");

		String[] priorityDbdicts = new String[] { "cm3r", "cm3rpage", "cm3t",
				"cm3tpage" };

		for (String priorityDbdict : priorityDbdicts) {
			Object dbdict = template.get(DBDictService.DBDICT, priorityDbdict);
			if (dbdict != null) {
				SMMap dbdictMap = (SMMap) dbdict;
				DBDict des = (DBDict) dbdictMap.get(DBDictService.DESCRIPTOR);
				boolean makeAlias = true;
				Field priorityCode = DBDictUtil.getFieldByName("priority.code",
						des.getField());
				if (priorityCode != null) {
					makeAlias = false;
				}

				if (makeAlias) {
					Field priority = DBDictUtil.getFieldByName("priority",
							des.getField());
					if (priority != null) {
						Field aliasField = (Field) priority.clone();
						aliasField.setName("priority.code");
						aliasField.setSql_field_options(new SqlFieldOptions());
						aliasField.setParentField(priority.getParentField());
						DBDictUtil.insertField(des, aliasField,
								Collections.EMPTY_LIST);
						template.update(DBDictService.DBDICT, dbdictMap);
						if (logger.isDebugEnabled()) {
							logger.debug(
									"The priority.code field was upgraded for the {} dbdict.",
									priorityDbdict);
						}
					}
				} else {
					if (logger.isDebugEnabled()) {
						logger.debug(
								"The priority field already exists in the {} dbdict.  It could not be added.",
								priorityDbdict);
					}
				}

			}
		}

		logger.info("  Finished upgrading Priority Code.");
	}

}
